package com.baosight.xCyber.input;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.baosight.xCyber.model.TagNode;
import com.baosight.xCyber.util.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

/**
 * 导入csv文件解析
 * @author 吴起航
 */
@Component
public class ExcelLoad {

    private Logger logger = LoggerFactory.getLogger(ExcelLoad.class);
    private Map<String, TagNode> resultMap = new TreeMap<>();

    public String importExcel(String filePath,Map<String,Object> propertyMap) {

        String fileName = filePath.substring(filePath.lastIndexOf("_")+1,filePath.lastIndexOf("."));
        //String filePath = applicationHome.getDir()+"/code/"+fileName;
        try {
            File excel = new File(filePath);
            if(excel.exists() && excel.isFile()){
                FileInputStream fis = new FileInputStream(excel);
                resultMap = ExcelUtil.getDataByExcel(fis, filePath,propertyMap);
                logger.info(fileName+":already load excel data");
            }
        } catch (FileNotFoundException e) {
            logger.error(fileName+":在路径"+filePath+"下未检测到指定文件："+e.getMessage());
        } catch (Exception e) {
            logger.error(fileName+":文件解析异常"+e.getMessage());
        }
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        String[] filterList=new String[]{
                "showName",
                "itemFlag",
                "remarkName",
                "source",
                "serviceId",
                "unit",
                "parentId",
                "treeName",
                "desc",
                "extraParam",
                "lazyLoad"
        };
        Arrays.stream(filterList).forEach(filter.getExcludes()::add);


        return JSONObject.toJSONString(resultMap.get("root"), filter);
    }

    public Map<String, TagNode> getMainMap(){
        return ExcelUtil.mainMap;
    }

    public Map<String, TagNode> getTreeMap(){
        return ExcelUtil.treeMap;
    }
}
